<template>
  <div>
    <div v-if="showPay">
      <md-popup id="popup-container" v-model="value" position="bottom" :has-mask="true" prevent-scroll @hide="cancel">
        <md-popup-title-bar title="支付" ok-text cancel-text="取消" @confirm="confirm" @cancel="cancel"></md-popup-title-bar>
        <div class="taxiPayType">
          <p class="taxiPayAlt">
            ￥
            <span>{{lastOrderAmt}}</span>
          </p>
          <p class="taxiPayDetail">
            费用明细
            <md-icon name="wdqb-more" slot="left" class="quxiao_icon" @click="taxiCost"></md-icon>
          </p>
          <div class="payType">
            <ul class="choice-payment-method">
              <li @click="paybalance">
                <img src="@/assets/imgs/snyc_zf_yezf.png" />
                <span>余额支付</span>
                <b>
                  <em>余额</em>
                  <i class="choice-payment-right" :class="{active:paymentMethod == 'balance'}"></i>
                </b>
              </li>
              <li @click="payWx">
                <img src="@/assets/imgs/cz_wx_icon@2x.png" />
                <span>微信支付</span>
                <b>
                  <i class="choice-payment-right" :class="{active:paymentMethod == 'wechat'||paymentMethod == 'miniprogram'||paymentMethod=='h5wx'}"></i>
                </b>
              </li>
              <li @click="payAli" v-if="hasAlipay">
                <img src="@/assets/imgs/cz_zfb_icon@2x.png" />
                <span>支付宝支付</span>
                <b>
                  <i class="choice-payment-right" :class="{active:paymentMethod == 'alipay'}"></i>
                </b>
              </li>
            </ul>
          </div>
          <p class="taxi_cost_text" @click="costError">费用有误，通知司机</p>
          <p class="taxi_pay" @click="createBalancePaybox">去支付</p>
        </div>
      </md-popup>
    </div>
    <div v-else>
      <md-popup id="popup-container" v-model="paypwdvalue" position="bottom" :has-mask="true" prevent-scroll @hide="cancel">
        <md-popup-title-bar title="请输入支付密码" ok-text cancel-text="取消" @cancel="paypwdcancel"></md-popup-title-bar>
        <div class="pay_box">
          <md-codebox :mask="true" :autofocus="true" :maxlength="6" v-model="payPwd" @submit="paysubmit" />
        </div>
      </md-popup>
    </div>
    <md-dialog title="确认" :closable="false" v-model="actDialog.open" :btns="actDialog.btns">请确认支付是否已经完成</md-dialog>
  </div>
</template>
<script>
/**
 * 此组件根据服务器返回的支付方式
 */
import '@/assets/svgs/wdqb-more.svg';
import { Popup, PopupTitleBar, Picker, Icon, Codebox, Toast, Dialog } from 'mand-mobile';
import { mapGetters, mapActions, mapMutations } from 'vuex';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import Utils from '@/common/pakjUtils';
import http from '@/common/http';
import Loading from '@/components/loading';
import { Base64 } from 'js-base64';
var CryptoJS = require('crypto-js');
var moment = require('moment');
moment.locale('zh-cn');
const STORAGE_CALLED_PAY = 'CALLED_PAY';
const STORAGE_ORDER_NO = 'ORDER_NO';
export default {
  name: 'time-selector',
  components: {
    [Popup.name]: Popup,
    [PopupTitleBar.name]: PopupTitleBar,
    [Icon.name]: Icon,
    [Codebox.name]: Codebox,
    [Picker.name]: Picker,
    [Toast.name]: Toast,
    [Dialog.name]: Dialog
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    appendTo: {
      default: () => document.body
    }
  },
  data() {
    return {
      actDialog: {
        open: false,
        btns: [
          {
            text: '重新支付',
            handler: this.onActCancel
          },
          {
            text: '已完成支付',
            handler: this.onActConfirm
          }
        ]
      },
      PaymentStatusTimer: '',
      paymentMethod: 'balance',
      showPay: true,
      paypwdvalue: false,
      payPwd: '',
      couponId: '',
      payType: '1004' // 支付方式
    };
  },
  created() {
    let calledPay = localStorage.getItem(STORAGE_CALLED_PAY);
    if (calledPay === '1') {
      this.actDialog.open = true;
    }
  },
  methods: {
    ...mapActions(['taxiSubmitPayment']),
    onActConfirm() {
      localStorage.removeItem(STORAGE_CALLED_PAY);
      localStorage.removeItem(STORAGE_ORDER_NO);
      this.actDialog.open = false;
      Loading.show();
      this.queryPaymentStatus();
      // setTimeout(() => {
      //     Loading.hide();
      //     this.$store
      //         .dispatch('checkPaymentStatus', this.$route.query.orderno)
      //         .then(() => {
      //             this.$emit('submit');
      //         })
      //         .catch(reason => {
      //             Dialog.alert({
      //                 title: '错误',
      //                 content: '支付失败',
      //                 confirmText: '确定'
      //             });
      //         });
      // }, 1000);
    },
    onActCancel() {
      localStorage.removeItem(STORAGE_CALLED_PAY);
      localStorage.removeItem(STORAGE_ORDER_NO);
      this.actDialog.open = false;
    },
    confirm() {
      this.value = false;
      this.$emit('submit');
    },
    cancel() {
      this.value = false;
    },
    paypwdcancel() {
      this.paypwdvalue = false;
      this.showPay = true;
      this.value = true;
    },
    createBalancePaybox() {
      if (this.paymentMethod === 'balance') {
        // 余额支付
        this.showPay = false;
        this.paypwdvalue = true;
        this.value = false;
      } else if (this.paymentMethod === 'wechat') {
        // 微信支付
        if (this.getTaxiOrderInfoData.coupon_type === '2') {
          // 有优惠券不使用
          this.couponId = '';
        } else {
          this.couponId = this.getTaxiOrderInfoData.coupon_id;
        }
        let p = {
          order_no: this.$route.query.orderno,
          pay_type: '1001',
          user_coupon_id: this.couponId
        };
        this.taxiSubmitPayment(p)
          .then(() => {
            let params = this.taxiSubmitPaymentData.JSPParam;
            wx.config({
              debug: false,
              appId: params['appId'],
              timestamp: params['timestamp'],
              nonceStr: params['noncestr'],
              signature: params['signature'],
              jsApiList: ['chooseWXPay']
            });
            wx.ready(() => {
              wx.chooseWXPay({
                timestamp: params['timestamp'],
                nonceStr: params['noncestr'],
                package: 'prepay_id=' + params['package'], // TODO May need remove 'prepay\_id='
                signType: 'MD5', // TODO If this didn't work . Use 'SHA1'.
                paySign: params['paySign'],
                success: res => {
                  if (res.errMsg === 'chooseWXPay:ok') {
                    this.queryPaymentStatus();
                    // this.$emit('submit');
                  }
                },
                fail: res => {
                  this.$store
                    .dispatch('checkPaymentStatus', this.$route.query.orderno)
                    .then(() => {
                      this.$emit('submit');
                    })
                    .catch(reason => {
                      Dialog.alert({
                        title: '错误',
                        content: '支付失败',
                        confirmText: '确定'
                      });
                    });
                }
              });
            });
          })
          .catch(reason => {
            if (reason.message === '200008') {
              this.$emit('submit');
            } else {
              Dialog.alert({
                title: '错误',
                content: '支付失败',
                confirmText: '确定'
              });
            }
          });
      } else if (this.paymentMethod === 'miniprogram') {
        // 小程序支付
        Loading.show();
        if (this.getTaxiOrderInfoData.coupon_type === '2') {
          // 有优惠券不使用
          this.couponId = '';
        } else {
          this.couponId = this.getTaxiOrderInfoData.coupon_id;
        }
        let params = {
          order_no: this.$route.query.orderno,
          pay_type: '1001',
          user_coupon_id: this.couponId
        };
        this.taxiSubmitPayment(params)
          .then(res => {
            res.orderNo = this.$route.query.orderno;
            let jsonStr = JSON.stringify(res);
            let base64str = Base64.encode(jsonStr);
            wx.miniProgram.redirectTo({
              url: '/pages/payment/payment?info=' + base64str
            });
          })
          .catch(reason => {
            if (reason.message === '200008') {
              this.$emit('submit');
            } else {
              Dialog.alert({
                title: '错误',
                content: '支付失败',
                confirmText: '确定'
              });
            }
          });
      } else if (this.paymentMethod === 'h5wx') {
        // H5支付
        if (this.getTaxiOrderInfoData.coupon_type === '2') {
          // 有优惠券不使用
          this.couponId = '';
        } else {
          this.couponId = this.getTaxiOrderInfoData.coupon_id;
        }
        let p = {
          order_no: this.$route.query.orderno,
          pay_type: '1001',
          user_coupon_id: this.couponId
        };
        this.taxiSubmitPayment(p)
          .then(() => {
            localStorage.setItem(STORAGE_ORDER_NO, this.$route.query.orderno);
            localStorage.setItem(STORAGE_CALLED_PAY, '1');
            window.location.href = this.getH5wxPaymentInfo.JSPParam.mweb_url;
            this.actDialog.open = true;
          })
          .catch(reason => {
            if (reason.message === '200008') {
              this.$emit('submit');
            } else {
              Dialog.alert({
                title: '错误',
                content: '支付失败',
                confirmText: '确定'
              });
            }
          });
      } else if (this.paymentMethod === 'alipay') {
        // 支付宝支付
        if (this.getTaxiOrderInfoData.coupon_type === '2') {
          // 有优惠券不使用
          this.couponId = '';
        } else {
          this.couponId = this.getTaxiOrderInfoData.coupon_id;
        }
        let parameters = {
          order_no: this.$route.query.orderno,
          pay_type: '1002',
          user_coupon_id: this.couponId
        };
        this.taxiSubmitPayment(parameters)
          .then(() => {
            localStorage.setItem(STORAGE_ORDER_NO, this.$route.query.orderno);
            localStorage.setItem(STORAGE_CALLED_PAY, '1');
            let htmlStr = this.getH5wxPaymentInfo.AlipayBody;
            const div = document.createElement('div'); // 创建div
            div.innerHTML = htmlStr; // 将返回的form 放入div
            document.body.appendChild(div);
            document.forms[0].submit();
            this.actDialog.open = true;
          })
          .catch(reason => {
            if (reason.message === '200008') {
              this.$emit('submit');
            } else {
              Dialog.alert({
                title: '错误',
                content: '支付失败',
                confirmText: '确定'
              });
            }
          });
      }
    },
    paybalance() {
      // 选择余额支付
      this.paymentMethod = 'balance';
      this.payType = '1004';
    },
    payWx() {
      // 选择微信支付
      switch (Utils.getCurrentEnv()) {
        case 'mini':
          this.paymentMethod = 'miniprogram';
          break;
        case 'wx':
          this.paymentMethod = 'wechat';
          break;
        case 'h5':
          this.paymentMethod = 'h5wx';
          break;
      }
      this.payType = '1001';
    },
    payAli() {
      // 选择支付宝支付
      this.paymentMethod = 'alipay';
      this.payType = '1002';
    },
    paysubmit() {
      if (this.payPwd.length === 6) {
        this.createBalancePay();
      }
    },
    // 费用有误
    costError() {
      Dialog.confirm({
        title: '费用有误',
        content: '费用有误通知司机修改行程费用',
        confirmText: '是',
        cancelText: '否',
        onConfirm: () => {
          let params = {
            order_no: this.$route.query.orderno
          };
          Loading.show();
          http.post('/pakj/utaxi/refusePay', params).then(res => {
            Loading.hide();
            if (res.data.code === '000000') {
              this.$emit('submit');
            } else {
              Dialog.alert({
                title: '提示',
                content: res.data.msg,
                confirmText: '确定'
              });
            }
          });
        }
      });
    },
    createBalancePay() {
      let params = {
        payPwd: CryptoJS.MD5(this.payPwd).toString()
      };
      Loading.show();
      http.post('pakj/passenger/validatePayPwd', params).then(res => {
        this.paypwdvalue = false;
        this.showPay = true;
        this.code = false;
        Loading.hide();
        if (res.data.code === '000000') {
          this.taxiPay();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
        }
      });
    },
    // 费用明细
    taxiCost() {
      this.value = false;
      if (this.getTaxiOrderInfoData.coupon_type === '2') {
        this.$router.push({
          name: 'taxichargesDetails',
          query: {
            orderno: this.$route.query.orderno,
            user_coupon_id: ''
          }
        });
      } else {
        this.$router.push({
          name: 'taxichargesDetails',
          query: {
            orderno: this.$route.query.orderno,
            user_coupon_id: this.getTaxiOrderInfoData.coupon_id
          }
        });
      }
    },
    taxiPay() {
      if (this.getTaxiOrderInfoData.coupon_type === '2') {
        // 有优惠券不使用
        this.couponId = '';
      } else {
        this.couponId = this.getTaxiOrderInfoData.coupon_id;
      }
      let params = {
        order_no: this.$route.query.orderno,
        pay_type: this.payType,
        user_coupon_id: this.couponId
      };
      Loading.show();
      http.post('/pakj/utaxi/payOrder', params).then(res => {
        Loading.hide();
        console.log(res.data);
        if (res.data.code === '000000') {
          Dialog.alert({
            title: '提示',
            content: '支付成功',
            confirmText: '确定',
            onConfirm: () => {
              this.$emit('submit');
            }
          });
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
        }
      });
    },
    // 查询支付状态
    queryPaymentStatus() {
      let params = {
        type: '3',
        orderNo: this.$route.query.orderno
      };
      this.$store
        .dispatch('paymentStatus', params)
        .then(() => {
          Toast({
            content: '支付成功',
            duration: 2000,
            hasMask: true
          });
          Loading.hide();
          clearInterval(this.PaymentStatusTimer);
          setTimeout(() => {
            this.$emit('submit');
          }, 2000);
        })
        .catch(error => {
          let str = error.toString().split(':');
          let code = str[1].trim();
          let msgText = str[2];
          if (code === '5') {
            // 正在查询支付结果
            Loading.show('正在查询支付结果');
            this.PaymentStatusTimer = setInterval(() => {
              this.queryPaymentStatus();
            }, 5000);
          } else if (code === '4') {
            // 支付失败
            Toast({
              content: '支付失败',
              duration: 2000,
              hasMask: true
            });
            Loading.hide();
            clearInterval(this.PaymentStatusTimer);
          }
        });
    }
  },
  mounted() {
    if (this.appendTo) {
      this.appendTo.appendChild(this.$el);
    }
  },
  beforeDestroy() {
    if (this.appendTo) {
      this.appendTo.removeChild(this.$el);
    }
  },
  computed: {
    ...mapGetters(['getTaxiOrderInfoData', 'taxiSubmitPaymentData']),
    hasAlipay() {
      if (Utils.getCurrentEnv() === 'h5') {
        return true;
      } else {
        return false;
      }
    },
    lastOrderAmt() {
      var money = decryptByDESModeEBC(this.getTaxiOrderInfoData.last_order_amt);
      return money;
    }
  }
};
</script>

<style lang="stylus">
#popup-container {
  p {
    display: block;
    margin-block-start: 0px;
    margin-block-end: 0px;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
  }

  .taxiPayType {
    background-color: #fff;
  }

  .pay_box {
    background-color: #fff;
    height: 550px;
  }

  .taxiPayAlt {
    text-align: center;
    padding-top: 56px;
    font-size: 24px;
    color: #333;
  }

  .taxiPayAlt span {
    font-size: 40px;
  }

  .taxiPayDetail {
    text-align: center;
    font-size: 24px;
    color: #999;
    margin-top: 20px;
  }

  .choice-payment-method li {
    padding: 0px 30px;
    font-size: 26px;
    color: #666;
    line-height: 88px;
    height: 88px;
    border-bottom: #e0e0e0 solid 1px;
  }

  .choice-payment-method li img {
    width: 44px;
    height: 44px;
    position: relative;
    top: 12px;
  }

  .choice-payment-method li span {
    margin-left: 20px;
  }

  .choice-payment-method li b {
    float: right;
    color: #999999;
    font-weight: 400;
  }

  .choice-payment-method li b em {
    margin-right: 10px;
    font-style: normal;
  }

  .choice-payment-right {
    display: inline-block;
    background-color: #fff;
    width: 36px;
    height: 36px;
    border: 1px solid #e3e3e3;
    border-radius: 50%;
    position: relative;
    top: 12px;
  }

  .choice-payment-method li b .active {
    background: url('../../../assets/imgs/ddzf_icon_pre@2x.png') no-repeat center center;
    background-size: contain;
    border-color: #fff;
    width: 36px;
    height: 36px;
  }

  .taxi_pay {
    background-color: #ff6917;
    height: 98px;
    line-height: 98px;
    font-size: 36px;
    color: #fff;
    text-align: center;
  }

  .taxi_cost_text {
    color: #666;
    text-align: center;
    padding-top: 20px;
    font-size: 22px;
    padding-bottom: 20px;
  }

  .quxiao_icon {
    width: 24px;
    height: 24px;
    position: relative;
    top: 3px;
    margin-right: 8px;
  }

  .slider {
    width: 200vw;
    transform: translate3d(0, 0, 0);
    transition: transform 0.5s ease-in-out;

    .container {
      background-color: #fff;
      height: 432px;
      width: 100vw;
      float: left;
      font-size: 22px;

      .hint {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        height: 88px;
        font-size: 22px;
        color: color-text-caption;

        .hint-icon {
          width: 26px;
          height: 24px;
        }

        .theme-str {
          color: theme-color;
        }
      }

      .flex-box {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 88px;

        .waiting-hint {
          display: -webkit-box;
          font-size: 22px;

          .hint-icon {
            width: 26px;
            height: 24px;
          }

          .hint-str {
            color: theme-color;
          }

          .waiting-hint {
            color: color-text-caption;
            max-width: 25em;
            text-align: center;
          }
        }
      }
    }
  }
}
</style>
